// pages/match-preferences/match-preferences.js
const { get, post } = require('../../utils/api.js')
const { showError, showSuccess, showToast } = require('../../utils/util.js')

Page({
  data: {
    // 基本偏好设置
    preferences: {
      // 年龄范围
      ageRange: [22, 35],
      minAge: 18,
      maxAge: 60,
      
      // 身高范围
      heightRange: [160, 180],
      minHeight: 140,
      maxHeight: 200,
      
      // 距离范围
      maxDistance: 50, // km
      
      // 教育水平
      education: [],
      
      // 职业类型
      occupations: [],
      
      // 兴趣爱好匹配度
      interestMatchWeight: 70, // 百分比
      
      // 活跃度要求
      lastActiveWithin: 7, // 天数
      
      // 是否只看已认证用户
      onlyVerified: false,
      
      // 是否排除已互动用户
      excludeInteracted: true
    },
    
    // 智能推荐设置
    smartMatching: {
      enabled: true,
      compatibilityWeight: 80,
      personalityMatch: true,
      lifestyleMatch: true,
      valuesMatch: true
    },
    
    // 选项数据
    educationOptions: [
      { label: '高中及以下', value: 'highschool' },
      { label: '大专', value: 'college' },
      { label: '本科', value: 'bachelor' },
      { label: '硕士', value: 'master' },
      { label: '博士', value: 'doctor' }
    ],
    
    occupationCategories: [
      { label: 'IT/互联网', value: 'tech' },
      { label: '金融/投资', value: 'finance' },
      { label: '教育/培训', value: 'education' },
      { label: '医疗/健康', value: 'healthcare' },
      { label: '文化/媒体', value: 'media' },
      { label: '销售/市场', value: 'sales' },
      { label: '制造/工程', value: 'engineering' },
      { label: '服务业', value: 'service' },
      { label: '政府/公共', value: 'government' },
      { label: '自由职业', value: 'freelance' }
    ],
    
    lastActiveOptions: [
      { label: '1天内', value: 1 },
      { label: '3天内', value: 3 },
      { label: '1周内', value: 7 },
      { label: '2周内', value: 14 },
      { label: '1个月内', value: 30 }
    ],
    
    // UI状态
    loading: false,
    hasChanges: false,
    
    // 弹窗状态
    showEducationPopup: false,
    showOccupationPopup: false,
    showActivePopup: false,
    showResetDialog: false,
    
    // 智能建议
    suggestions: {
      show: false,
      items: []
    },
    
    // 预估匹配数量
    estimatedMatches: 0
  },

  onLoad() {
    this.loadPreferences()
    this.generateIntelligentSuggestions()
  },

  /**
   * 加载用户偏好设置
   */
  loadPreferences() {
    this.setData({ loading: true })
    
    get('/api/user/match-preferences')
      .then(data => {
        if (data && Object.keys(data).length > 0) {
          this.setData({
            preferences: { ...this.data.preferences, ...data.preferences },
            smartMatching: { ...this.data.smartMatching, ...data.smartMatching },
            loading: false
          })
        } else {
          // 没有保存的偏好，使用智能默认值
          this.setIntelligentDefaults()
        }
        this.updateEstimatedMatches()
      })
      .catch(error => {
        console.error('加载偏好设置失败:', error)
        this.setIntelligentDefaults()
      })
  },

  /**
   * 设置智能默认值
   */
  setIntelligentDefaults() {
    // 基于用户自身信息设置智能默认值
    get('/api/user/profile')
      .then(profile => {
        const age = this.calculateAge(profile.birthday)
        const height = parseInt(profile.height) || 170
        
        // 智能年龄范围：用户年龄±5岁
        const ageRange = [
          Math.max(18, age - 5),
          Math.min(60, age + 5)
        ]
        
        // 智能身高范围：基于性别设置合理范围
        let heightRange = [160, 180]
        if (profile.gender === 'female') {
          heightRange = [165, 185] // 女性偏好较高男性
        } else if (profile.gender === 'male') {
          heightRange = [150, Math.max(170, height)] // 男性范围更宽泛
        }
        
        this.setData({
          'preferences.ageRange': ageRange,
          'preferences.heightRange': heightRange,
          loading: false
        })
        
        this.updateEstimatedMatches()
      })
      .catch(() => {
        this.setData({ loading: false })
      })
  },

  /**
   * 计算年龄
   */
  calculateAge(birthday) {
    if (!birthday) return 25 // 默认年龄
    const today = new Date()
    const birthDate = new Date(birthday)
    let age = today.getFullYear() - birthDate.getFullYear()
    const monthDiff = today.getMonth() - birthDate.getMonth()
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--
    }
    return age
  },

  /**
   * 年龄范围变化
   */
  onAgeRangeChange(e) {
    const ageRange = e.detail.value
    this.setData({
      'preferences.ageRange': ageRange,
      hasChanges: true
    })
    this.updateEstimatedMatches()
  },

  /**
   * 身高范围变化
   */
  onHeightRangeChange(e) {
    const heightRange = e.detail.value
    this.setData({
      'preferences.heightRange': heightRange,
      hasChanges: true
    })
    this.updateEstimatedMatches()
  },

  /**
   * 距离滑块变化
   */
  onDistanceChange(e) {
    this.setData({
      'preferences.maxDistance': e.detail.value,
      hasChanges: true
    })
    this.updateEstimatedMatches()
  },

  /**
   * 兴趣匹配权重变化
   */
  onInterestWeightChange(e) {
    this.setData({
      'preferences.interestMatchWeight': e.detail.value,
      hasChanges: true
    })
  },

  /**
   * 兼容性权重变化
   */
  onCompatibilityWeightChange(e) {
    this.setData({
      'smartMatching.compatibilityWeight': e.detail.value,
      hasChanges: true
    })
  },

  /**
   * 开关设置变化
   */
  onSwitchChange(e) {
    const { type, field } = e.currentTarget.dataset
    const value = e.detail
    
    this.setData({
      [`${type}.${field}`]: value,
      hasChanges: true
    })
    
    if (type === 'preferences') {
      this.updateEstimatedMatches()
    }
  },

  /**
   * 显示教育选择器
   */
  showEducationSelector() {
    this.setData({ showEducationPopup: true })
  },

  /**
   * 教育选择确认
   */
  onEducationConfirm(e) {
    const education = e.detail.value
    this.setData({
      'preferences.education': education,
      showEducationPopup: false,
      hasChanges: true
    })
    this.updateEstimatedMatches()
  },

  /**
   * 切换教育选项
   */
  toggleEducation(e) {
    const value = e.currentTarget.dataset.name
    const currentEducation = [...this.data.preferences.education]
    const index = currentEducation.indexOf(value)
    
    if (index > -1) {
      currentEducation.splice(index, 1)
    } else {
      currentEducation.push(value)
    }
    
    this.setData({
      'preferences.education': currentEducation
    })
  },

  /**
   * 显示职业选择器
   */
  showOccupationSelector() {
    this.setData({ showOccupationPopup: true })
  },

  /**
   * 职业选择确认
   */
  onOccupationConfirm(e) {
    const occupations = e.detail.value
    this.setData({
      'preferences.occupations': occupations,
      showOccupationPopup: false,
      hasChanges: true
    })
    this.updateEstimatedMatches()
  },

  /**
   * 切换职业选项
   */
  toggleOccupation(e) {
    const value = e.currentTarget.dataset.name
    const currentOccupations = [...this.data.preferences.occupations]
    const index = currentOccupations.indexOf(value)
    
    if (index > -1) {
      currentOccupations.splice(index, 1)
    } else {
      currentOccupations.push(value)
    }
    
    this.setData({
      'preferences.occupations': currentOccupations
    })
  },

  /**
   * 显示活跃度选择器
   */
  showActiveSelector() {
    this.setData({ showActivePopup: true })
  },

  /**
   * 活跃度选择确认
   */
  onActiveConfirm(e) {
    const lastActiveWithin = e.detail.value
    this.setData({
      'preferences.lastActiveWithin': lastActiveWithin,
      showActivePopup: false,
      hasChanges: true
    })
    this.updateEstimatedMatches()
  },

  /**
   * 更新预估匹配数量
   */
  updateEstimatedMatches() {
    // 模拟计算预估匹配数量
    const { preferences } = this.data
    let baseCount = 1000
    
    // 年龄范围影响
    const ageRange = preferences.ageRange[1] - preferences.ageRange[0]
    baseCount = Math.floor(baseCount * (ageRange / 20))
    
    // 距离影响
    baseCount = Math.floor(baseCount * (preferences.maxDistance / 100))
    
    // 教育筛选影响
    if (preferences.education.length > 0) {
      baseCount = Math.floor(baseCount * 0.6)
    }
    
    // 职业筛选影响
    if (preferences.occupations.length > 0) {
      baseCount = Math.floor(baseCount * 0.7)
    }
    
    // 认证用户筛选影响
    if (preferences.onlyVerified) {
      baseCount = Math.floor(baseCount * 0.4)
    }
    
    // 活跃度影响
    const activeFactor = preferences.lastActiveWithin <= 7 ? 0.8 : 0.5
    baseCount = Math.floor(baseCount * activeFactor)
    
    this.setData({
      estimatedMatches: Math.max(10, baseCount)
    })
  },

  /**
   * 生成智能建议
   */
  generateIntelligentSuggestions() {
    get('/api/user/profile')
      .then(profile => {
        const suggestions = []
        
        // 基于用户资料生成建议
        if (!profile.education) {
          suggestions.push({
            type: 'education',
            title: '放宽学历要求',
            description: '建议不限制学历，可以遇到更多有趣的人',
            action: 'clearEducation'
          })
        }
        
        if (this.data.preferences.maxDistance < 30) {
          suggestions.push({
            type: 'distance',
            title: '扩大搜索范围',
            description: '建议将搜索距离扩大到50公里，增加匹配机会',
            action: 'expandDistance'
          })
        }
        
        if (this.data.preferences.interestMatchWeight > 80) {
          suggestions.push({
            type: 'interest',
            title: '适当降低兴趣权重',
            description: '过分注重兴趣可能错过合适的人，建议设为70%',
            action: 'adjustInterest'
          })
        }
        
        this.setData({
          'suggestions.items': suggestions,
          'suggestions.show': suggestions.length > 0
        })
      })
      .catch(error => {
        console.error('生成智能建议失败:', error)
      })
  },

  /**
   * 应用智能建议
   */
  applySuggestion(e) {
    const { action } = e.currentTarget.dataset
    
    switch (action) {
      case 'clearEducation':
        this.setData({
          'preferences.education': [],
          hasChanges: true
        })
        break
      case 'expandDistance':
        this.setData({
          'preferences.maxDistance': 50,
          hasChanges: true
        })
        break
      case 'adjustInterest':
        this.setData({
          'preferences.interestMatchWeight': 70,
          hasChanges: true
        })
        break
    }
    
    this.updateEstimatedMatches()
    this.generateIntelligentSuggestions()
    showSuccess('已应用建议')
  },

  /**
   * 关闭建议
   */
  closeSuggestions() {
    this.setData({
      'suggestions.show': false
    })
  },

  /**
   * 重置为推荐设置
   */
  resetToRecommended() {
    this.setData({ showResetDialog: true })
  },

  /**
   * 确认重置
   */
  confirmReset() {
    this.setData({ showResetDialog: false })
    this.setIntelligentDefaults()
    this.setData({ hasChanges: true })
    showSuccess('已重置为推荐设置')
  },

  /**
   * 取消重置
   */
  cancelReset() {
    this.setData({ showResetDialog: false })
  },

  /**
   * 保存偏好设置
   */
  savePreferences() {
    if (!this.data.hasChanges) {
      showToast('没有修改需要保存')
      return
    }
    
    this.setData({ loading: true })
    
    const saveData = {
      preferences: this.data.preferences,
      smartMatching: this.data.smartMatching
    }
    
    post('/api/user/match-preferences', saveData)
      .then(() => {
        showSuccess('偏好设置已保存')
        this.setData({
          hasChanges: false,
          loading: false
        })
        
        // 延迟返回
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      })
      .catch(error => {
        console.error('保存偏好设置失败:', error)
        showError('保存失败，请重试')
        this.setData({ loading: false })
      })
  },

  /**
   * 返回上一页
   */
  goBack() {
    if (this.data.hasChanges) {
      wx.showModal({
        title: '确认离开',
        content: '您有未保存的修改，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
    } else {
      wx.navigateBack()
    }
  },

  /**
   * 弹窗关闭处理
   */
  hideEducationPopup() {
    this.setData({ showEducationPopup: false })
  },

  hideOccupationPopup() {
    this.setData({ showOccupationPopup: false })
  },

  hideActivePopup() {
    this.setData({ showActivePopup: false })
  }
})